package com.mach.platform.service.js.iot;

import com.mach.platform.util.SqlHelper;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class SqlHelperJS extends  SqlHelper{

    private ScriptEngine eng = null;

    public SqlHelperJS(ScriptEngine eng){
        this.eng = eng;
    }

    public static SqlHelperJS getBySource(DataSource dataSource,ScriptEngine eng){
        SqlHelperJS hlp = new SqlHelperJS(eng);
        if(dataSource == null){
            return null;
        }
        hlp.setDataSource(dataSource);
        return hlp;
    }

    private AtomicInteger addIx  = new AtomicInteger(0);
    public Ctx qry(String sql){

        Ctx ctx = null;
        try {
            String jsObjName = "jsObjName_" + Thread.currentThread().getId() + "_" + System.currentTimeMillis() + "_" + this.addIx.getAndAdd(1);
            Map<Object, Map<String, Object>> data = this.query(sql);
            try {
                this.eng.put(jsObjName, data);
                //System.out.println("jsObjName=" + jsObjName + " data="+data); //debug
                ctx = (Ctx)this.eng.eval("Ctx.frMap("+jsObjName+",'"+jsObjName+"');");
                this.eng.put(jsObjName,null);
            } catch (ScriptException e) {
                e.printStackTrace();
            }finally {
                try {
                    //this.eng.eval("" + jsObjName +"=null;");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ctx;
    }
}
